<?php


namespace app\app\controller;

use think\Db;
use app\common\library\DataUtils;

class index extends Baseapp
{
    /**
     * 上传图片
     */
    // todo 转换成webp 看图片压缩
    public function upload_img()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');

        if ($info) {

            $logo = '/' . 'uploads' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();
            if ($d['type'] == 1) {
                $d['path'] = conf("wechat", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = conf("wechat", "url") . $d['path'];
            }
            $return = $this->appEncrypt($d);
            msg(0, "获取成功", $return);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }
    //上传图片 并压缩
    public function upload_img2()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');

        if ($info) {
            $originalPath = ROOT_PATH . 'public' . '/' . 'uploads' . '/' . $info->getSaveName();
            $originalLogo = '/' . 'uploads' . '/' . $info->getSaveName();

            // 生成WebP格式的图片
            $webpPath = convertToWebP($originalPath);

            if ($webpPath) {
                // 如果WebP转换成功，使用WebP图片路径
                $logo = str_replace(ROOT_PATH . 'public', '', $webpPath);
                $fileExtension = 'webp';
            } else {
                // 如果转换失败，使用原图片
                $logo = $originalLogo;
                $fileExtension = $info->getExtension();
            }

            $datas = $info->getInfo();

            $img['path'] = $logo;
            $img['mime'] = 'image/webp'; // 更新MIME类型为webp
            $img['name'] = pathinfo($datas['name'], PATHINFO_FILENAME) . '.webp'; // 修改文件名为webp格式
            $img['size'] = file_exists(ROOT_PATH . 'public' . $logo) ? filesize(ROOT_PATH . 'public' . $logo) : $datas['size'];
            $img['sha1'] = $info->hash('sha1');
            $img['md5'] = $info->hash('md5');
            $img['driver'] = 'local';
            $img['create_time'] = time();
            $img['update_time'] = time();
            $img['status'] = 1;
            $img['ext'] = $fileExtension;

            $id = Db::name('attachment')->insertGetId($img);

            // 如果WebP转换成功，可以选择删除原图
            if ($webpPath && $webpPath !== $originalPath) {
                // 删除原图，只保留WebP格式
                @unlink($originalPath);
            }

            //todo 关闭oss
//        if (config('is_oss') == 1) {
//            upload_local_file($id);
//        }
            $d = db('attachment')->where('id', $id)->find();
            $d['path'] = conf("wechat", "url") . $d['path'];

            $return = $this->appEncrypt($d);
            msg(0, "获取成功", $return);

        } else {
            echo $files->getError();
        }
    }


    /**
     * 上传视频
     */
    public function upload_video()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploadsvideo');

        if ($info) {

            $logo = '/' . 'uploadsvideo' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();
            if ($d['type'] == 1) {
                $d['path'] = conf("wechat", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = conf("wechat", "url") . $d['path'];
            }
            $return = $this->appEncrypt($d);
            msg(0, "获取成功", $return);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }


    /**
     * 获取各项配置
     */
    public function getConfigAdmin()
    {
        $data = $this->request->param();

        $data = $this->appDecrypt($data);

        $cate_name = array(
            'fx_hb',
            'logo',
            'xcx_name',
            'yg_tx_money',
            'shop_tx_money',
            'kf_dh',
            'slimg1',
            'slimg2',
            'slimg3',
//            'slimg4',
            'max_video',
            'max_img',
            'is_kg'
        );
        foreach ($cate_name as $k => $v) {
            $return[$v] = config('site.' . $v);
        }
        $banner1 = Db::name('banner')
            ->where([
                'status' => 1,
                'is_del' => 0,
                'type' => 1
            ])
            ->order('sort desc')->select();

        $banner2 = Db::name('banner')
            ->where([
                'status' => 1,
                'is_del' => 0,
                'type' => 2
            ])
            ->order('sort desc')->select();

        $return['banner1'] = $banner1;
        $return['banner2'] = $banner2;

        //{:config('site.yg_tx_money')}
        $shop_tx_desc = '1、当月累计' . config('site.shop_tx_money') . '元以内可在线提现，超过' . config('site.shop_tx_money') . '元后线下提现 2、申请提现后预计到账约2-3个工作日';
        //{:config('site.yg_tx_money')}
        $yg_tx_desc = '1、当月累计' . config('site.yg_tx_money') . '元以内可在线提现，超过' . config('site.yg_tx_money') . '元后线下提现 2、申请提现后预计到账约2-3个工作日';
        //shop_is_tx 商家员工是否可提现
        //jz_is_tx 兼职员工是否可提现
        //qz_is_tx 全职员工是否线上提现

        $return['shop_tx_desc'] = $shop_tx_desc;
        $return['yg_tx_desc'] = $yg_tx_desc;
        $return['shop_is_tx'] = config('site.shop_is_tx');
        $return['jz_is_tx'] = config('site.jz_is_tx');
        $return['qz_is_tx'] = config('site.qz_is_tx');

        $return = $this->appEncrypt($return);
        msg(0, '查询完成', $return);
    }

    /**
     * 获取openid
     */
    public function wxLogin()
    {
        $code = $this->request->param("code");
        $appId = config('wechat.appID');
        $secret = config('wechat.AppSecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = lmcurl($url);
        $res = json_decode($res, true);
        $return = $this->appEncrypt($res);
        msg(0, "成功", $return);
    }

    //申请商家
    public function addShop()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        Db::startTrans();
        try {
            $username = Db::name('member')->where('username', '=', $data['username'])->find();
            if ($username) {
                msg(-4, '账号已存在', '');
            }
            $shop_info = Db::name('shop')
                ->where('openid', '=', $data['openid'])
                ->find();
            //0待审核 1审核通过 2账户关闭  3审核失败
            if ($shop_info && in_array($shop_info['status'], [0, 1, 2])) {
                msg(-2, '你已提交', '');
            }
            $salesperson = Db::name('salesperson')
                ->where('tg_no', '=', $data['tg_no'])
                ->find();
            if (!$salesperson) {
                msg(-3, '推广码不存在', '');
            }
            if ($shop_info) {
                $insert_shop = array(
                    'people' => $data['people'],
                    'phone' => $data['phone'],
                    'sf_id' => $data['sf_id'],
                    'sf_img1' => $data['sf_img1'],
                    'sf_img2' => $data['sf_img2'],
                    'shop_name' => $data['shop_name'],
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'area' => $data['area'],
                    'address' => $data['address'],
                    'shop_img' => $data['shop_img'],
                    'jq_img' => $data['jq_img'],
                    'rz_img' => $data['rz_img'],
                    'salesperson_id' => $salesperson['id'],
                    'tg_no' => $data['tg_no'],
                    'longitude' => $data['longitude'],
                    'latitude' => $data['latitude'],
                    'status' => 0,
                    'mp' => $data['mp'],
                    'reason_refusal' => '',
                    'cn_img' => $data['cn_img'],
                );
                Db::name('shop')->where([
                    ['openid', '=', $data['openid']],
                    ['is_del', '=', 0]
                ])->update($insert_shop);
                $shop_info = Db::name('shop')->where([
                    ['openid', '=', $data['openid']],
                    ['is_del', '=', 0]
                ])->find();
            } else {
                //插入微信
                $member_wx = deuser($this->request->ip(), $data);
                //插入账号
                $member_info = addMember($data['username'], $data['password'], $data['username'], 2, $member_wx);
                //商家信息
                $insert_shop = array(
                    'people' => $data['people'],
                    'phone' => $data['phone'],
                    'sf_id' => $data['sf_id'],
                    'sf_img1' => $data['sf_img1'],
                    'sf_img2' => $data['sf_img2'],
                    'shop_name' => $data['shop_name'],
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'area' => $data['area'],
                    'address' => $data['address'],
                    'shop_img' => $data['shop_img'],
                    'jq_img' => $data['jq_img'],
                    'rz_img' => $data['rz_img'],
                    'salesperson_id' => $salesperson['id'],
                    'create_time' => time(),
                    'tg_no' => $data['tg_no'],
                    'openid' => $data['openid'],
                    'member_id' => $member_info['id'],
                    'longitude' => $data['longitude'],
                    'latitude' => $data['latitude'],
                    'mp' => $data['mp'],
                );
                $shop_id = Db::name('shop')->insertGetId($insert_shop);

                $shop_info = Db::name('shop')->find($shop_id);
            }
            $return_data = $this->appEncrypt($shop_info);
            Db::commit();
            msg(0, '提交完成', $return_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    /**
     * 获取员工banner图
     */
    public function getBanner()
    {
        $data = Db::name('banner')
            ->where([
                'status' => 1,
                'is_del' => 0,
                'type' => 1
            ])
            ->order('sort desc')->select();
        $return_data = $this->appEncrypt($data);
        msg(0, '查询成功', $return_data);
    }

    /**
     * 获取商家banner图
     */
    public function getBanner2()
    {
        $data = Db::name('banner')
            ->where([
                'status' => 1,
                'is_del' => 0,
                'type' => 2
            ])
            ->order('sort desc')->select();
        $return_data = $this->appEncrypt($data);
        msg(0, '查询成功', $return_data);
    }

    //账号登录 绑定 微信
    public function login1()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);

        $username = trim($data['account']);
        $password = trim($data['password']);
        //插入微信
        $openid = $data['openid'];
        $member_wx = deuser($this->request->ip(), $data);
        $member = Db::name('member')->where([
            ['username', '=', $username]
        ])->find();
        if (!$member) {
            msg(-1, '账号不存在', '', '');
        }
        if ($member['password'] != encrypt_password($password, $member['salt'])) {
            msg(-1, '密码不正确', '', '');
        }

        Db::name('member')->where([
            ['id', '=', $member['id']]
        ])->update([
            'member_wx_id' => $member_wx['id'],
            'openid' => $member_wx['openid'],
        ]);

        //todo 账号只绑定一商户号 或者 业务员
        if ($member['role'] == 1) {
            Db::name('member')->where([
                ['member_wx_id', '=', $member_wx['id']],
                ['id', '<>', $member['id']],
                ['role', '=', 1],
            ])->update([
                'member_wx_id' => null,
                'openid' => null
            ]);
        }
        if ($member['role'] == 2) {
            Db::name('member')->where([
                ['member_wx_id', '=', $member_wx['id']],
                ['id', '<>', $member['id']],
                ['role', '=', 2],
            ])->update([
                'member_wx_id' => null,
                'openid' => null
            ]);
        }


        //role 1员工 2商家 3全部
        $return_data['member_info'] = $member;
        $salesperson = Db::name('salesperson')
            ->where('member_id', '=', $member['id'])
            ->find();
        $shop = Db::name('shop')->where('member_id', '=', $member['id'])->find();
        $return_data['salesperson'] = $salesperson;
        $return_data['shop'] = $shop;

        if ($member['role'] == 3) {
            $return_data = $this->appEncrypt($return_data);
            msg(0, '查询完成', $return_data, '');
        } else {
            //todo 增加账号审核
            $token = md5(time() . $password);
            Db::name('member')->update([
                'id' => $member['id'],
                'access_token' => $token
            ]);
            $return_data['member_info']['access_token'] = $token;
            $return_data = $this->appEncrypt($return_data);
            msg(0, '登陆成功', $return_data, '');
        }
    }

    //openid 是否绑定账号和绑定账号的信息
    public function getAccountByOpenid()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        $openid = $data['openid'];
        $member_wx = deuser($this->request->ip(), $data);
        $member_info = Db::name('member')
            ->where('openid', '=', $member_wx['openid'])
            ->find();
        if ($member_info) {

            $salesperson = Db::name('salesperson')->where('member_id', '=', $member_info['id'])->find();
            $shop = Db::name('shop')->where('member_id', '=', $member_info['id'])->find();

            $return_data['member_info'] = $member_info;
            $return_data['salesperson'] = $salesperson;
            $return_data['shop'] = $shop;

            if ($member_info['role'] == 3) {
                $return_data = $this->appEncrypt($return_data);
                msg(0, '查询完成', $return_data, '');
            } else {
                //todo 增加账号审核
                $token = md5(time() . $member_info['password']);
                Db::name('member')->update([
                    'id' => $member_info['id'],
                    'access_token' => $token
                ]);
                $return_data['member_info']['access_token'] = $token;
                $return_data = $this->appEncrypt($return_data);
                msg(0, '登陆成功', $return_data, '');
            }
        } else {
            msg(-1, '未绑定账号', '', '');
        }
    }

    /**
     * 多角色选择登录
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function loginTypeRole()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);

        //member_id role_type  1员工 2商家
        $member_info = Db::name('member')->where('id', '=', $data['id'])->find();
        if ($data['role_type'] == 1) {
            $salesperson = Db::name('salesperson')
                ->where('member_id', '=', $data['member_id'])
                ->find();
            if (!$salesperson) {
                msg(-1, '员工账号不存在', '');
            }
            if ($salesperson['status'] != 1) {
                msg(-2, '员工账号异常', '');
            }
            $token = md5(time() . $member_info['password']);
            Db::name('member')->update([
                'id' => $member_info['id'],
                'access_token' => $token
            ]);
            $return_data['access_token'] = $token;
        }
        if ($data['role_type'] == 2) {
            $shop = Db::name('shop')
                ->where('member_id', '=', $data['member_id'])
                ->find();
            if (!$shop) {
                msg(-1, '商家账号不存在', '');
            }
            if ($shop['status'] != 1) {
                msg(-2, '商家账号异常', '');
            }
            $token = md5(time() . $member_info['password']);
            Db::name('member')->update([
                'id' => $member_info['id'],
                'access_token' => $token
            ]);
            $return_data['access_token'] = $token;
        }
        $return_data = $this->appEncrypt($return_data);
        msg(0, '查询完成', $return_data, '');
    }

    //获取常见问题
    public function getQuestion()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        $page = isset($data['page']) && $data['page'] > 0 ? (int)$data['page'] : 1;
        $length = isset($data['limit']) && $data['limit'] > 0 ? (int)$data['limit'] : 20;

        $data_list = Db::name('question')
            ->where([
                'is_del' => 0,
                'status' => 1,
            ])->order('sort desc')
            ->paginate($length, false, ['page' => $page])
            ->each(function ($item) {
                return $item;
            });

        $data_list = $this->appEncrypt($data_list);
        msg(0, '查询成功', $data_list);
    }

    //通过坐标获取位置信息
    public function getAddressByLocation()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getAddressByLocation2($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            $data_list['data']['location']['lat'] = $data['latitude'];
            $data_list['data']['location']['lng'] = $data['longitude'];
            $return_data = $this->appEncrypt($data_list['data']['address_component']);
            msg(0, '查询成功', $return_data);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //获取商家审核状态
    public function shopStatus()
    {
        //0待审核 1审核通过 2账户关闭  3审核失败
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        $member_info = Db::name('member')->where([
            'openid' => $data['openid'],
            'role' => 2
        ])->find();
        if ($member_info) {
            $shop_info = Db::name('shop')->where([
                'member_id' => $member_info['id']
            ])->find();
            $shop_info['username'] = $member_info['username'];
            $shop_info['password'] = '';
            $return_data = $this->appEncrypt($shop_info);
            if ($shop_info['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $return_data);
            }
            if ($shop_info['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过，重新提交', $return_data);
            }
            if ($shop_info['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $return_data);
            }
            msg(1, '你已申请，等待审核', $return_data);
        }

//        $shop_info = Db::name('shop')->where([
//            'openid' => $data['openid']
//        ])->find();
//        if ($shop_info) {
//            $member_info = Db::name('member')->find($shop_info['member_id']);
//            $shop_info['username'] = $member_info['username'];
//            $shop_info['password'] = '';
//            $return_data = $this->appEncrypt($shop_info);
//            if ($shop_info['status'] == 1) {
//                //返回数据
//                msg(0, '申请已通过', $return_data);
//            }
//            if ($shop_info['status'] == 3) {
//                //返回数据
//                msg(-3, '审核不通过，重新提交', $return_data);
//            }
//            if ($shop_info['status'] == 2) {
//                //返回数据
//                msg(-2, '账户冻结,请联系管理员', $return_data);
//            }
//
//            msg(1, '你已申请，等待审核', $return_data);
//        }
        msg(-1, '未申请', '');
    }

    //获取账户信息
    public function member_info()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        $member_info = Db::name('member')
            ->where('access_token', '=', $data['access_token'])
            ->find();
        if (!$member_info) {
            msg(-100, '账号不存在', '');
        }
        $shop_info = Db::name('shop')
            ->where('member_id', '=', $member_info['id'])
            ->find();
        if ($shop_info) {
            $gh = Db::name('shop_gh')->where([
                ['shop_id', '=', $shop_info['id']]
            ])->column('gh');
            $gh = implode(',', $gh);
            $shop_info['gh'] = $gh;
        }
        $salesperson = Db::name('salesperson')
            ->where('member_id', '=', $member_info['id'])
            ->find();
        $return['member_info'] = $member_info;
        $return['shop_info'] = $shop_info;
        $return['yw_info'] = $salesperson;
        $return_data = $this->appEncrypt($return);
        msg(0, '查询成功', $return_data);
    }

    //通过openid 获取绑定的账号
    public function getMemberListByOpenid()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        $return_list = Db::name('member')->where([
            'status' => 1,
            'openid' => $data['openid']
        ])->select();
        $return_data = $this->appEncrypt($return_list);
        msg(0, '查询成功', $return_data);
    }

    //通过获取Member的token
    public function getMemberToken()
    {
        $data = $this->request->param();
        //openid username id
        $member = Db::name('member')->find($data['id']);
        $token = md5(time() . $member['password']);
        Db::name('member')->update([
            'id' => $member['id'],
            'access_token' => $token
        ]);
        $member = Db::name('member')->find($data['id']);
        $return_data = $this->appEncrypt($member);
        msg(0, '查询成功', $return_data);
    }

    //判断手机号是否唯一
    public function isOne()
    {
        $data = $this->request->param();
        $data = $this->appDecrypt($data);
        $is_phone = Db::name('order')->where([
            ['phone', '=', $data['phone']],
        ])->find();
        if ($is_phone) {
            msg(-1, '当前手机号已存在', '');
        }
        msg(0, '当前手机号可用', '');
    }


    // 大屏相关接口
    public function areaList()
    {
        $city_list = array(
            '0' => '全部城区',
            '1' => '北京市',
            '2' => '天津市',
        );
        $db_cities = Db::name('shop')
            ->distinct(true)
            ->where('city', '<>', '')
            ->where('city', 'not null')
            ->order('city')
            ->column('city');
        // 将查询结果添加到现有列表中
        foreach ($db_cities as $city) {
            if (!in_array($city, $city_list)) {
                $city_list[] = $city;
            }
        }
        $index = count($city_list);
        foreach ($db_cities as $city) {
            if (!in_array($city, $city_list)) {
                $city_list[$index] = $city;
                $index++;
            }
        }


        msg(0, '查询成功', $city_list);
    }


    public function index1()
    {
        $data = $this->request->param();
        $city = $data['city'];
        if ($city != '全部城区') {
            $where[] = ['province|city', '=', $city];
        }
        $shop_num_list = [];
        $return_rq = [];
        $rq_list = getLastSixMonths();
        //获取每月的时间戳
        foreach ($rq_list as $k => $v) {
            $ri_list[] = [];
            $rqc_list = getMonthTimestampRange($v['display2']);
            $return_rq[] = $v['month'];

            $shop_num_list[] = Db::name('shop')
                ->where($where)
                ->where([
                    ['create_time', 'between', [$rqc_list['start_timestamp'], $rqc_list['end_timestamp']]]
                ])
                ->count();
        }
        $return['return_rq'] = $return_rq;
        $return['shop_num_list'] = $shop_num_list;
        msg(0, '查询成功', $return);
    }

    public function index2()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $where = [];
        if ($city != '全部城区') {
            $where[] = ['province|city', '=', $city];
        }
        $shop_list = Db::name('shop')
            ->where($where)
            ->field('id,shop_name,order_num')
            ->limit('10')
            ->order('order_num desc')
            ->select();
        msg(0, '查询成功', $shop_list);
    }

    public function index3()
    {
        $data = $this->request->param();
        $city = $data['city'];
//        $where=[];
//        if ($city != '全部城区') {
//            $where[] = ['province|city', '=', $city];
//        }
        $result = Db::name('salesperson')
            ->alias('sp')
            ->field('sp.id, sp.name, COUNT(s.id) as shop_count')
            ->leftJoin('shop s', 'sp.id = s.salesperson_id')
            ->group('sp.id, sp.name')
            ->order('shop_count', 'desc')
            ->limit(10)
            ->select();

        msg(0, '查询成功', $result);
    }

    public function index4()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $shop_where[] = ['id', '>', 0];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        //获取门店的id
        $shop_ids = Db::name('shop')->where($shop_where)->column('id');
        //
        $order_ids = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids]
        ])->column('id');
        $date1 = DataUtils::getTimeRange('today');
        $date2 = DataUtils::getTimeRange('yesterday');
        $date3 = DataUtils::getTimeRange('last_month');
        $money[] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date1['start_time'], $date1['end_time']]]
        ])->sum('money');
        $money[] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date2['start_time'], $date2['end_time']]]
        ])->sum('money');
        $money[] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date3['start_time'], $date3['end_time']]]
        ])->sum('money');
        $money[] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
        ])->sum('money');

        $title_list = array(
            '今日返佣', '昨日返佣', '上月返佣', '累计总返佣',
        );
        foreach ($money as $k => $v) {
            $money2 = sprintf("%.2f", $v);
            $return[] = [
                'title' => $title_list[$k],
                'money' => $money2
            ];
        }
        msg(0, '查询成功', $return);
    }

    public function index5()
    {
        $data = $this->request->param();
        $shop_where[] = ['id', '>', 0];
        $city = $data['city'];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        $data1 = DataUtils::getTimeRange('this_month');
        $data2 = DataUtils::getTimeRange('last_month');

        $num[] = Db::name('shop')->where($shop_where)->count();
        $num[] = Db::name('shop')
            ->where($shop_where)
            ->where([
                ['create_time', 'between', [$data1['start_time'], $data1['end_time']]]
            ])
            ->count();
        $num[] = Db::name('shop')
            ->where($shop_where)
            ->where([
                ['create_time', 'between', [$data2['start_time'], $data2['end_time']]]
            ])->count();
        $title_list = array(
            '当前门店总数', '本月新增门店', '上月新增门店'
        );
        foreach ($num as $k => $v) {
            $return[] = [
                'title' => $title_list[$k],
                'num' => $v
            ];
        }
        msg(0, '查询成功', $return);
    }

    public function index6()
    {
        $data = $this->request->param();
        $shop_where[] = ['id', '>', 0];
        $city = $data['city'];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        $shop_ids = Db::name('shop')
            ->where($shop_where)
            ->column('id');

        $data1 = DataUtils::getTimeRange('today');
        $data2 = DataUtils::getTimeRange('yesterday');
        $data3 = DataUtils::getTimeRange('this_month');
        $data4 = DataUtils::getTimeRange('last_month');

        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data1['start_time'], $data1['end_time']]]
        ])->count();
        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data2['start_time'], $data2['end_time']]]
        ])->count();
        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data3['start_time'], $data3['end_time']]]
        ])->count();
        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data4['start_time'], $data4['end_time']]]
        ])->count();

        $title_list = array(
            '今日开卡数据', '昨日开卡数据', '本月开卡数据', '上月开卡数据'
        );
        foreach ($num as $k => $v) {
            $list[] = [
                'title' => $title_list[$k],
                'num' => $v
            ];
        }
        //, '总开卡数据'
        $zk_num = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
        ])->count();
        $zk = array(
            'title' => '总开卡数据',
            'num' => $zk_num
        );
        $return['zk'] = $zk;
        $return['data_list'] = $list;

        msg(0, '查询成功', $return);
    }

    public function index7()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $shop_where[] = ['id', '>', 0];
        $type = $data['type'];//1最近10天 2最近10个月
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }

        $shop_ids = Db::name('shop')
            ->where($shop_where)
            ->column('id');
        //销户数量
        $num1 = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['is_yc', '=', 1],
            ['yc', '=', '销户'],
        ])->count();
        //销户金额
        $num2 = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['is_yc', '=', 1],
        ])->value('money1 + money2');
        if (!$num2) {
            $num2 = 0;
        }
        if ($type == 2) {
            $rq_list = DataUtils::getLastSixMonths();
        } else {
            $rq_list = DataUtils::getLastTenDays();
        }
        $data_list = [];
        foreach ($rq_list as $k => $v) {
            $timestampRange = DataUtils::getTimestampRange($v['date']);
            $order_num = Db::name('order')
                ->where([
                    ['shop_id', 'in', $shop_ids],
                    ['create_time', 'between', [$timestampRange['start_time'], $timestampRange['end_time']]]
                ])
                ->count();
            $data_list['data'][] = $v['display'];
            $data_list['order_num'][] = $order_num;
        }
        $return['num1'] = $num1;
        $return['num2'] = $num2;
        $return['data_list'] = $data_list;
        msg(0, '查询成功', $return);

    }

    public function index8()
    {
        $data = $this->request->param();
        $city = $data['city'];
        if ($city != '全部城区' && $city) {
            $where[] = ['province|city', '=', $city];
        }
        $shop_num_list = [];
        $return_rq = [];
        $rq_list = getLastSixMonths();
        //获取每月的时间戳
        foreach ($rq_list as $k => $v) {
            $ri_list[] = [];
            $rqc_list = getMonthTimestampRange($v['display2']);
            $return_rq[] = $v['month'];

            $shop_num_list[] = Db::name('shop')
                ->where($where)
                ->where([
                    ['create_time', 'between', [$rqc_list['start_timestamp'], $rqc_list['end_timestamp']]]
                ])
                ->count();
        }
        $return['return_rq'] = $return_rq;
        $return['shop_num_list'] = $shop_num_list;
        msg(0, '查询成功', $return);
    }

    public function index9()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $shop_where[] = ['id', '>', 0];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        $shop_ids = Db::name('shop')
            ->where($shop_where)
            ->column('id');
        $sum_num = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids]
        ])->count();
        //待审核 已通过 未通过
        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['status', '=', 0],
        ])->count();
        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['status', '=', 1],
        ])->count();
        $num[] = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['status', '=', 2],
        ])->count();
        $title = array('待审核', '已通过', '未通过');

        $color = array('rgba(0, 140, 255, 1)', 'rgba(51, 204, 204, 1)', 'rgba(255, 209, 86, 1)');


        $return_data = array();
        foreach ($num as $k => $v) {
            $return_data[$k]['name'] = $title[$k];
            $return_data[$k]['value'] = (int)(($v / $sum_num) * 100);
            $return_data[$k]['itemStyle'] = array('color' => $color[$k]);
        }
        msg(0, '查询成功', $return_data);
    }

    public function index9_2()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $shop_where[] = ['id', '>', 0];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        $shop_ids = Db::name('shop')
            ->where($shop_where)
            ->column('id');

        $package_list = Db::name('package')->where([
            'is_del' => 0
        ])->select();
        $color = array('rgba(0, 140, 255, 1)', 'rgba(51, 204, 204, 1)', 'rgba(255, 209, 86, 1)');


        $time_scope = DataUtils::getTimestampRange(date('Y-m-d'));
        $return_data = array();
        $index=0;
        foreach ($package_list as $k => $v) {
            $order_num = Db::name('order')->where([
                ['shop_id', 'in', $shop_ids],
                ['package_id', '=', $v['id']],
//                   ['create_time','between',[$time_scope['start_time'],$time_scope['end_time']]]
//                    ['status', '=', 2],
            ])->count();
            if ($order_num) {
                $return_data[$index]['name'] = $v['name'];
                $return_data[$index]['value'] = $order_num;
                $return_data[$index]['itemStyle'] = array('color' => $color[$k % 3]);
                $index++;
            }
        }
        msg(0, '查询成功', $return_data);
    }

    public function index10()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $shop_where[] = ['id', '>', 0];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        $shop_ids = Db::name('shop')
            ->where($shop_where)
            ->column('id');
        $ri_list = DataUtils::getLastSixMonths(5);

        $riqi = [];
        $return_sh_num = [];
        $return_shtg = [];
        foreach ($ri_list as $k => $v) {
            $timestampRange = DataUtils::getTimestampRange($v['date']);
            $sh_num = Db::name('order')->where([
                ['shop_id', 'in', $shop_ids],
                ['status', 'in', [1, 2]],
                ['create_time', 'between', [$timestampRange['start_time'], $timestampRange['end_time']]]
            ])->count();
            $sh_num2 = Db::name('order')->where([
                ['shop_id', 'in', $shop_ids],
                ['status', 'in', [2]],
                ['create_time', 'between', [$timestampRange['start_time'], $timestampRange['end_time']]]
            ])->count();

            $riqi[] = $v['month'];
            $return_sh_num[] = $sh_num;
            $return_shtg[] = $sh_num2;
        }
        $return['riqi'] = $riqi;
        $return['sh_num'] = $return_sh_num;
        $return['sh_num2'] = $return_shtg;
        msg(0, '查询成功', $return);
    }

    // 沉默门店数据排名
    public function index11()
    {
        $data = $this->request->param();
        $city = $data['city'];

        $time_in = DataUtils::getRecentDaysRange();
        $shop_list_ids = Db::name('order')->where([
            ['create_time', 'between', [$time_in['start_timestamp'], $time_in['end_timestamp']]]
        ])->column('shop_id');
        $where[] = ['id', 'not in', $shop_list_ids];
//        $where[] = ['status', 'in', [1,2]];
        $data_list = Db::name('shop')->where($where)->select();
        foreach ($data_list as $k => $v) {
            $salesperson_info = Db::name('salesperson')->find($v['salesperson_id']);
            $data_list[$k]['sale'] = $salesperson_info['name'];
        }
        msg(0, '编辑成功', $data_list);

    }

    public function cIndex()
    {
        $a = Db::name('shop')->where([
            ['is_del', '=', 0],
            ['status', 'in', [1, 2]],
        ])->count();

        $b = Db::name('salesperson')->count();

        $c = Db::name('shop')->where([
            ['is_del', '=', 0],
            ['status', 'in', [0]],
        ])->count();

        $d = Db::name('order')->where([
            ['status', '=', 0],
        ])->count();

        $data['a'] = $a;
        $data['b'] = $b;
        $data['c'] = $c;
        $data['d'] = $d;
        msg(0, '查询更改', $data);
    }

    public function cIndex2()
    {
        $data = $this->request->param();
        $shop_where[] = ['id', '>', 0];

        //获取门店的id
        $shop_ids = Db::name('shop')->where($shop_where)->column('id');
        //
        $order_ids = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids]
        ])->column('id');
        $date1 = DataUtils::getTimeRange('today');
        $date2 = DataUtils::getTimeRange('yesterday');
        $date3 = DataUtils::getTimeRange('this_month');
        $date4 = DataUtils::getTimeRange('last_month');
        $money['a'] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date1['start_time'], $date1['end_time']]]
        ])->sum('money');
        $money['b'] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date2['start_time'], $date2['end_time']]]
        ])->sum('money');
        $money['c'] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date3['start_time'], $date3['end_time']]]
        ])->sum('money');
        $money['d'] = Db::name('member_finance')->where([
            ['order_id', 'in', $order_ids],
            ['is_count', '=', 1],
            ['create_time', 'between', [$date4['start_time'], $date4['end_time']]]
        ])->sum('money');

        foreach ($money as $k => $v) {
            $money[$k] = sprintf("%.2f", $v);
        }
        msg(0, '查询成功', $money);
    }


    public function cIndex3()
    {
        $data = $this->request->param();
        $shop_where[] = ['id', '>', 0];
        $city = $data['city'];
        if ($city != '全部城区' && $city) {
            $shop_where[] = ['province|city', '=', $city];
        }
        $shop_ids = Db::name('shop')
            ->where($shop_where)
            ->column('id');

        $data1 = DataUtils::getTimeRange('today');
        $data2 = DataUtils::getTimeRange('yesterday');
        $data3 = DataUtils::getTimeRange('this_month');
        $data4 = DataUtils::getTimeRange('last_month');

        $a = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data1['start_time'], $data1['end_time']]]
        ])->count();
        $b = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data2['start_time'], $data2['end_time']]]
        ])->count();
        $c = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data3['start_time'], $data3['end_time']]]
        ])->count();
        $d = Db::name('order')->where([
            ['shop_id', 'in', $shop_ids],
            ['create_time', 'between', [$data4['start_time'], $data4['end_time']]]
        ])->count();
        $return['a'] = $a;
        $return['b'] = $b;
        $return['c'] = $c;
        $return['d'] = $d;


        msg(0, '查询成功', $return);
    }

    public function getbar()
    {
        $rq_list = DataUtils::getLastTenDays(29);
        $data1 = [];
        $data2 = [];
        foreach ($rq_list as $k => $v) {
            $order_num = Db::name('order')->where([
                ['create_time', 'between', [$v['startTimestamp'], $v['endTimestamp']]]
            ])->count();
            $data1[] = $v['display'];
            $data2[] = $order_num;
        }
        $return_data['data1'] = $data1;
        $return_data['data2'] = $data2;
        msg(0, '查询更改', $return_data);
    }

    public function getbar2()
    {
        $order_ids = Db::name('order')->column('id');

        $rq_list = DataUtils::getLastTenDays(29);
        $data1 = [];
        $data2 = [];

        foreach ($rq_list as $k => $v) {
            $order_num = Db::name('member_finance')->where([
//                ['order_id', 'in', $order_ids],
                ['type', 'in', [1, 2, 7]],
                ['is_count', '=', 1],
                ['create_time', 'between', [$v['startTimestamp'], $v['endTimestamp']]]
            ])->sum('money');
            $data1[] = $v['display'];
            $data2[] = $order_num;
        }
        $return_data['data1'] = $data1;
        $return_data['data2'] = $data2;
        msg(0, '查询更改', $return_data);
    }

    // 商家导入迁移
    public function ccshop()
    {
        $dhop_copy = Db::name('shop_copy1')->select();
        foreach ($dhop_copy as $k => $v) {
            //导入用户表
            $member_info = addMember($v['dlzh'], '123456', $v['phone'], 2, null);
            //商家表
            $insert_shop = array(
                'people' => $v['people'],
                'phone' => $v['phone'],
                'sf_id' => $v['sf_id'],
                'shop_name' => $v['people'],
                'province' => '北京市',
                'city' => '北京市',
                'area' => '',
                'salesperson_id' => $v['salesperson_id'],
                'create_time' => time(),
                'status_time' => time(),
                'member_id' => $member_info['id'],
                'is_dr' => 1,
                'gh' => $v['gh'],
                'bk_num' => 10,
                'status' => 1,
            );
            $shop_id = Db::name('shop')->insertGetId($insert_shop);
            //工号表
            $insert_shop_gh = array(
                'shop_id' => $shop_id,
                'province' => '天津市',
                'city' => '天津市',
                'create_time' => time(),
                'yys' => '广电',
                'gh' => $v['gh']
            );
            Db::name('shop_gh')->insertGetId($insert_shop_gh);
        }
        msg(0, '提交完成', $insert_shop_gh);
    }

    public function ccshop2()
    {
//        $shop_list = Db::name('shop')->where([
//            ['is_dr', '=', 1],
//            ['phone', '>', 0],
//        ])->select();
//        foreach ($shop_list as $k => $v) {
//            Db::name('shop')->update([
//                'id' => $v['id'],
//                'phone' => number_format((float)$v['phone'], 0, '', ''),
//            ]);
//        }
//        $shop_list = Db::name('member')->where([
//            ['tx_phone', '>', 0],
//        ])->select();
//        foreach ($shop_list as $k => $v) {
//            Db::name('member')->update([
//                'id' => $v['id'],
//                'tx_phone' => number_format((float)$v['tx_phone'], 0, '', ''),
//                'username' => number_format((float)$v['username'], 0, '', ''),
//            ]);
//        }
        Db::name('shop_gh')->where('gh', '=', null)->delete();
    }

}